import 'dart:async';

import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:sonora/bloc/base/sj_base_bloc.dart';
import 'package:sonora/bloc/userInfo/sj_user_info_event.dart';
import 'package:sonora/bloc/userInfo/sj_user_info_state.dart';
import 'package:sonora/models/sj_broad_caster_data.dart';
import 'package:sonora/models/sj_works_model.dart';
import 'package:sonora/utils/sj_storage_utils.dart';

class SjUserInfoBloc extends SjBaseBloc<SjUserInfoEvent, SjUserInfoState> {
  SjUserInfoBloc() : super(const SjUserInfoState()) {
    on<SjUserInfoEventInitial>(_onInitial);
    on<SjUserInfoEventLoaded>(_onLoadedData);
    on<SjUserInfoEventClickLikeButton>(_onClickLikeButton);
    on<SjUserInfoEventLoadWorksList>(_onLoadWorksList);
  }

  FutureOr<void> _onInitial(
      SjUserInfoEventInitial event, Emitter<SjUserInfoState> emit) async {
    emit(state.copyWith(loading: true));
  }

  FutureOr<void> _onLoadedData(
      SjUserInfoEventLoaded event, Emitter<SjUserInfoState> emit) async {
    emit(state.copyWith(caster: event.casterData));
  }

  FutureOr<void> _onClickLikeButton(SjUserInfoEventClickLikeButton event,
      Emitter<SjUserInfoState> emit) async {
    List<SjWorksModel>? updateWorksList =
        List<SjWorksModel>.from(state.worksList ?? []);
    if (updateWorksList.isNotEmpty) {
      SjWorksModel w = updateWorksList.firstWhere((element) => element.worksId == event.worksId);
      int index = updateWorksList.indexOf(w);
      w = w.copyWith(isLiked: !event.isLiked);
      int followed = 0;
      int liked = 0;
      if (event.isLiked) {
        if (w.followed != null && w.followed! > 0) {
          followed = w.followed! - 1;
        }

        if (w.liked != null && w.liked! > 0) {
          liked = w.liked! - 1;
        }
      } else {
        if (w.followed == null) {
          followed = 1;
        } else {
          followed = w.followed! + 1;
        }

        if (w.liked == null) {
          liked = 1;
        } else {
          liked = w.liked! + 1;
        }
      }
      w = w.copyWith(followed: followed, liked: liked);
      updateWorksList[index] = w;
      emit(state.copyWith(worksList: updateWorksList));
      SjStorageUtils.updateWorksList(updateWorksList);
    }
  }
    FutureOr<void> _onLoadWorksList(
      SjUserInfoEventLoadWorksList event, Emitter<SjUserInfoState> emit) async {
    try {
      String userId = event.userId;
      final list = await SjStorageUtils.getWorksByUserId(userId);
      if (list != null && list.length == 1) {
        list.add(const SjWorksModel(isPlaceholder: true));
      }
      emit(state.copyWith(worksList: list));
    } catch (e) {
      emit(state.copyWith(loading: false));
    }
  }
}
